/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.wechat.web;

import java.io.File;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
//import com.thinkgem.jeesite.common.utils.JedisUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.boxin.ims.modules.wechat.entity.RecommendConfig;
import com.boxin.ims.modules.wechat.service.RecommendConfigService;
import com.boxin.ims.modules.wechat.utils.WechatUtils;

/**
 * 三级推广配置文件Controller
 * @author zhangshanshan
 * @version 2016-03-14
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/wechat/recommendConfig")
public class RecommendConfigController extends BaseController {

	@Autowired
	private RecommendConfigService recommendConfigService;
	
	@ModelAttribute
	public RecommendConfig get(@RequestParam(required=false) Long id) {
		if (id != null){
			return recommendConfigService.get(id);
		}else{
			return new RecommendConfig();
		}
	}
	
	@RequiresPermissions("wechat:recommendConfig:view")
	@RequestMapping(value = {"list", ""})
	public String list(RecommendConfig recommendConfig, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			recommendConfig.setUserId(user.getId());
		}
        Page<RecommendConfig> page = recommendConfigService.find(new Page<RecommendConfig>(request, response), recommendConfig); 
        model.addAttribute("page", page);
		return "modules/wechat/recommendConfigList";
	}

	@RequiresPermissions("wechat:recommendConfig:view")
	@RequestMapping(value = "form")
	public String form(RecommendConfig recommendConfig, Model model) {
	
		User user = UserUtils.getUser();
		
		/*RecommendConfig config = recommendConfigService.getByUserId(user.getId());
		if(config!=null && !user.isAdmin()){
			recommendConfig = config;
			String key = "recommend_config_"+config.getUserId();
			JedisUtils.setObject(key, recommendConfig, 0);
			CacheUtils.put(key, recommendConfig);
		} 
		if(recommendConfig.getUserId() == null){
			recommendConfig.setUserId(user.getId());
		}*/
		
		recommendConfig.setUserId(user.getId());
		model.addAttribute("recommendConfig", recommendConfig);
		return "modules/wechat/recommendConfigForm";
	}
	
	@RequiresPermissions("wechat:recommendConfig:edit")
	@RequestMapping(value = "save")
	public String save(@RequestParam("picFile") MultipartFile picFile, @RequestParam("picFile1") MultipartFile picFile1, HttpServletRequest request, 
						RecommendConfig recommendConfig, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, recommendConfig)){
			return form(recommendConfig, model);
		}
		
		if(StringUtils.isNotBlank(picFile.getOriginalFilename())){
			recommendConfig.setRecommendPic(uploadPicFile(picFile, "recommend", request));
		}
		if(StringUtils.isNotBlank(picFile1.getOriginalFilename())){
			recommendConfig.setRankPic(uploadPicFile(picFile1, "rank_pic", request));
		}
		
		//判断新添加的活动是否开启，如开启，则将其他属于此用户的活动关闭
		if(RecommendConfig.YES.equals(recommendConfig.getIsOpen())){
			recommendConfigService.closeAllByUserId(recommendConfig.getUserId());
		}
		
		recommendConfigService.save(recommendConfig);
		
		//判断新添加的活动是否开启，如开启，将活动放到缓存中
		if(RecommendConfig.YES.equals(recommendConfig.getIsOpen())){
			String key = "recommend_config_"+recommendConfig.getUserId();
//			JedisUtils.setObject(key, recommendConfig, 0);
			CacheUtils.put(key, recommendConfig);
		}
		
		addMessage(redirectAttributes, "保存三级推广配置文件'" + recommendConfig.getName() + "'成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/recommendConfig/?repage";
	}
	
	/**
	 * 上传图片
	 * @param picFile
	 * @param picName
	 * @param request
	 * @return
	 */
	public String uploadPicFile(MultipartFile picFile, String picName, HttpServletRequest request) {
		String fileName = "";
		if(picFile != null && picFile.getOriginalFilename().length()>4){
			String picFilePath = WechatUtils.getRecommendSavePath(request)+File.separator;
			FileUtils.createDirectory(picFilePath);
			String sname = picFile.getOriginalFilename();
			String fileType = sname.substring(sname.lastIndexOf("."));
			String fname  = UserUtils.getUser().getLoginName()+	"_"+picName+"_"+System.currentTimeMillis()+fileType;
			File file = new File(picFilePath+fname);
			try {
				picFile.transferTo(file);
				fileName = file.getName();
			} catch (Exception e) {
				System.out.println("上传文件失败:"+picFilePath+fname);
			}
		}
		return fileName;
	}
	
	@RequiresPermissions("wechat:recommendConfig:edit")
	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		recommendConfigService.delete(id);
		addMessage(redirectAttributes, "删除三级推广配置文件成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/recommendConfig/?repage";
	}

	
	@RequestMapping(value = "openConfig")
	public String openConfig(Long id, RedirectAttributes redirectAttributes) {
		
		RecommendConfig recommendConfig = recommendConfigService.get(id);
		recommendConfigService.closeAllByUserId(recommendConfig.getUserId());//关闭用户下的所有活动
		recommendConfigService.openRecommendConfigById(id);
		
		//将从缓存中删除
		String key = "recommend_config_"+recommendConfig.getUserId();
//		JedisUtils.del(key);
		CacheUtils.remove(key);
		
		addMessage(redirectAttributes, "开启成功");
		
		return "redirect:"+Global.ADMIN_PATH+"/wechat/recommendConfig/?repage";
	}
	
	@RequestMapping(value = "closeConfig")
	public String closeConfig(Long id, RedirectAttributes redirectAttributes) {

		RecommendConfig recommendConfig = recommendConfigService.get(id);
		recommendConfigService.closeAllByUserId(recommendConfig.getUserId());//关闭用户下的所有活动
		
		//将从缓存中删除
		String key = "recommend_config_"+recommendConfig.getUserId();
//		JedisUtils.del(key);
		CacheUtils.remove(key);
		
		addMessage(redirectAttributes, "关闭成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/recommendConfig/?repage";
	}
	
}
